from __future__ import annotations

from dataclasses import dataclass
from math import tan, radians
from typing import Optional, Dict, Any

from gssgca.core.standard_loader import provider


@dataclass
class SheetPileSelection:
    model: str
    section_modulus_cm3_m: float
    max_bending_Mk_kNm_m: float
    ok: bool
    note: str


def select_sheet_pile(
    excavation_depth_m: float,
    unit_weight_kN_m3: float = 18.0,
    active_coeff: float | None = None,
    allowable_stress_MPa: float = 215.0,
    embed_ratio: float = 0.5,
    catalog_key: str = "sheet_piles",
) -> SheetPileSelection:
    """钢板桩选型与强度校核（简化）。

    - 土压力取三角形：p_max = K_a·γ·H
    - 结果力 R = 1/2·p_max·H，弯矩 M ≈ R·H/3
    - 入土深度 = embed_ratio·H
    - 选型：满足 M ≤ f_allow · W  （W为截面模数/每米墙长）
    """

    H = excavation_depth_m
    Ka = active_coeff if active_coeff is not None else 0.33
    p_max = Ka * unit_weight_kN_m3 * H
    R = 0.5 * p_max * H  # kN/m
    M = R * (H / 3.0)  # kN·m/m

    catalog = provider._load_json("sheet_pile_catalog.json").get(catalog_key, [])
    selected: Optional[Dict[str, Any]] = None
    for it in sorted(catalog, key=lambda x: x.get("W_cm3_per_m", 0.0)):
        W = float(it.get("W_cm3_per_m", 0.0))  # cm³/m
        W_mm3_per_m = W * 1000.0  # 转为 mm³/m
        capacity_kNm = allowable_stress_MPa * W_mm3_per_m / 1e6  # MPa*mm³= N·mm => kN·mm -> kN·m
        if capacity_kNm >= M:
            selected = it
            break
    if not selected and catalog:
        selected = max(catalog, key=lambda x: x.get("W_cm3_per_m", 0.0))
        note = "取最大规格仍不足，请提高入土或复核计算"
        ok = False
    elif selected:
        note = "满足强度要求，需做位移与稳定分析"
        ok = True
    else:
        return SheetPileSelection("N/A", 0.0, M, False, "未找到型录")

    return SheetPileSelection(
        model=str(selected.get("model", "unknown")),
        section_modulus_cm3_m=float(selected.get("W_cm3_per_m", 0.0)),
        max_bending_Mk_kNm_m=M,
        ok=ok,
        note=note,
    )


